﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using System.Net.Http;
using Native.Sdk.Cqp.EventArgs;
using Native.Sdk.Cqp.Interface;
using cqp.tian.bgtz.me.Code.Enum;
using Native.Sdk.Cqp;
using cqp.tian.bgtz.me.Code.Common;
using System.Net;
using Newtonsoft.Json.Linq;
using cqp.tian.bgtz.me.Code.JsonCard;

namespace cqp.tian.bgtz.me.Code
{
    public class Event_AppEnable : IAppEnable
    {
        private static CQApi _cqApi = null;
        System.Timers.Timer t = new System.Timers.Timer(10000); //设置时间间隔为10秒
        private static readonly object LockObj = new object();

        public void AppEnable(object sender, CQAppEnableEventArgs e)
        {
            if (_cqApi == null)
            {
                _cqApi = e.CQApi;
            }

            t.Elapsed += new System.Timers.ElapsedEventHandler(GetNewChapter);
            t.AutoReset = true; //每到指定时间Elapsed事件是触发一次（false），还是一直触发（true）
            t.Enabled = true;
            t.Start();
        }

        private void GetNewChapter(object sender, System.EventArgs e)
        {

            lock (LockObj)
            {
                //获取更新的书籍信息
                var bookList = ReadXml.GetBooksData();

                //遍历每一本书籍
                foreach (var book in bookList)
                {
                    //起点最新章节
                    var newChapter = GetCatalog(book.Id);

                    //本地存储的最新章节
                    var latestChapter = ReadLatestChapter(book.Code);

                    //如果起点的最新章节发布时间要大于本地的最新章节发布时间，说明已更新
                    if (latestChapter == null || DateTime.Parse(newChapter.ChapterTime) > DateTime.Parse(latestChapter.ChapterTime))
                    {
                        var url = book.TransferUrl + "?bookId=" + book.Id + "&chapterId=" + newChapter.Id;//打开起点APP的中转页
                        var picture = book.CoverImageUrl + "/" + book.Code + ".jpg";//封面图片
                        foreach (var g in book.Group)
                        {
                            //发送更新消息
                            _cqApi.SendGroupMessage(long.Parse(g.GroupNo), (g.IsAtAll ? CQApi.CQCode_AtAll().ToSendString() + "\n" : string.Empty) + (g.IsSendImage ? CQApi.CQCode_Image(g.ImageName).ToSendString() + "\n" : string.Empty) + "最新章节：\"" + newChapter.ChapterName + "\" \n发布时间：" + newChapter.ChapterTime + " \n本章字数：" + newChapter.WordNumber);

                            //发送更新分享链接
                            if (newChapter.ChapterName.IndexOf("第", StringComparison.Ordinal) > -1 && newChapter.ChapterName.IndexOf("章", StringComparison.Ordinal) > -1 && newChapter.ChapterName.IndexOf("章", StringComparison.Ordinal) > newChapter.ChapterName.IndexOf("第", StringComparison.Ordinal) && g.IsSendShare)
                                //CQApi.SendGroupMessage(long.Parse(g.GroupNo), CQApi.CQCode_ShareLink(url, newChapter.ChapterName, "发布时间:" + newChapter.ChapterTime + "\n本章字数:" + newChapter.WordNumber, picture));
                                _cqApi.SendGroupMessage(long.Parse(g.GroupNo), CQApi.CQEnCode("[CQ:json,data=" + GetCardInfoJson(newChapter, url, picture) + "]",false));
                        }
                        //把最新章节信息写入本地
                        WriteLatestChapter(newChapter, book.Code);
                    }

                    //本次获取的最新章节名称
                    LogHelper.WriteMsgInLog("书名：" + book.Name + "，章节名称：" + newChapter.ChapterName, book.Code);
                }
            }
        }

        private static Chapter GetCatalog(string Id)
        {
            //章节实体类
            var chapter = new Chapter();

            //起点获取章节列表的请求地址
            var url = "https://book.qidian.com/ajax/book/category?bookId=" + Id;

            //发送get请求
            var response = HttpHelper.CreateGetHttpResponse(url, 5000, string.Empty, null);

            //使用流获取response的数据
            var sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            var tmpResult = sr.ReadToEnd();

            //使用jobject处理数据，根据服务器返回的json结构，获取最新章节
            var obj = (JObject)JsonConvert.DeserializeObject(tmpResult);

            var vsArray = new JArray();

            if (!string.IsNullOrWhiteSpace(obj["data"]["vs"].ToString()))
            {
                vsArray = JArray.Parse(obj["data"]["vs"].ToString());
            }

            JArray csArray;
            csArray = JArray.Parse(vsArray[vsArray.Count - 1]["cs"].ToString());

            var newChapter = JObject.Parse(csArray[csArray.Count - 1].ToString());

            //设置最新章节的相关信息
            chapter.ChapterName = newChapter["cN"].ToString();
            chapter.ChapterTime = newChapter["uT"].ToString();
            chapter.WordNumber = int.Parse(newChapter["cnt"].ToString());
            chapter.Id = newChapter["id"].ToString();

            //返回起点最新章节
            return chapter;
        }

        /// <summary>
        /// 读取存储的最新章节
        /// </summary>
        /// <returns></returns>
        private static Chapter ReadLatestChapter(string bookCode)
        {
            var filePath = CommonApi.MainPath + "LatestChapter\\" + bookCode + ".json";

            //如果文件不存在，就新建该文件，并返回null，表示这本书是第一次获取更新  
            if (!File.Exists(filePath))
            {
                var sr = File.CreateText(filePath);
                sr.Close();

                return null;
            }

            //读取本地的最新章节json文件
            var json = File.ReadAllText(filePath);

            //反序列化到章节实体类
            var chapter = JsonConvert.DeserializeObject<Chapter>(json);

            //返回本地存储的最新章节
            return chapter;
        }

        /// <summary>
        /// 获取json卡片信息
        /// </summary>
        /// <param name="chapter">最新章节信息</param>
        /// <param name="jumpUrl">将要跳转的Url</param>
        /// <param name="iconUrl">图标Url</param>
        /// <returns></returns>
        private static string GetCardInfoJson(Chapter chapter, string jumpUrl, string iconUrl)
        {

            try
            {
                var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                var random = new Random();
                var config = new Config()
                {
                    autosize = true,
                    forward = true,
                    token = "b3d3d7ddf1f620b32dccec9662ca7f1c",
                    type = "normal",
                    ctime = (long)ts.TotalSeconds
                };
                var extra = new Extra()
                {
                    appid = 1105910806,
                    app_type = 1,
                    uin = 1045740922,
                    msg_seq = random.Next(1000000, 9999999)
                };
                var news = new News()
                {
                    app_type = 1,
                    appid = 1105910806,
                    desc = "发布时间:" + chapter.ChapterTime + "\n本章字数:" + chapter.WordNumber,
                    jumpUrl = jumpUrl,
                    source_icon = iconUrl,
                    tag = "报更童子",
                    title = chapter.ChapterName,
                    action = "",
                    android_pkg_name = "",
                    preview = "",
                    source_url = ""
                };
                var meta = new Meta() { news = news };

                var cardInfo = new CardInfo()
                {
                    app = "com.tencent.structmsg",
                    config = config,
                    desc = "新闻",
                    extra = extra,
                    meta = meta,
                    prompt = "[已更新]" + chapter.ChapterName,
                    ver = "0.0.0.1",
                    view = "news"
                };

                LogHelper.WriteMsgInLog(JsonConvert.SerializeObject(cardInfo), "xhdz");

                return JsonConvert.SerializeObject(cardInfo);
            }
            catch (Exception e)
            {
                LogHelper.WriteMsgInLog("错误信息:" + e.Message + "\n" + e.StackTrace, "xhdz");
                return string.Empty;
            }


        }

        /// <summary>
        /// 写入最新的章节信息
        /// </summary>
        /// <param name="chapter">章节信息</param>
        /// <param name="bookCode">书籍code</param>
        private static void WriteLatestChapter(Chapter chapter, string bookCode)
        {
            //文件地址
            var filePath = CommonApi.MainPath + "LatestChapter\\" + bookCode + ".json";

            //序列化为json字符串
            var json = JsonConvert.SerializeObject(chapter);

            //写入文件
            File.WriteAllText(filePath, json);
        }
    }
}
